package control;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import model.BO_Mp3tag;

public class XmlHandler {
	public static List<BO_Mp3tag> getMp3TagObjects(String xmlURL){	
		List<BO_Mp3tag> result = new ArrayList<BO_Mp3tag>();
		NodeList fileNodes = getXMLNodes(xmlURL,"file");			
		for (int i = 0; i < fileNodes.getLength(); i++) {
			Node fileNode  = fileNodes.item(i);
			if(fileNode.getNodeType()==Node.ELEMENT_NODE){				
				BO_Mp3tag objMp3tag = new BO_Mp3tag();
				objMp3tag.setTitle(getValueByChildNodeName(fileNode,"title"));
				objMp3tag.setArtist(getValueByChildNodeName(fileNode,"artist"));
				objMp3tag.setAnho(getValueByChildNodeName(fileNode,"year"));
				objMp3tag.setGenero(getValueByChildNodeName(fileNode,"genre"));
				objMp3tag.setRatingWmp(getValueByChildNodeName(fileNode,"ratingWmp"));
				objMp3tag.setFullPath(getValueByChildNodeName(fileNode,"fullPath"));
				result.add(objMp3tag);
			}				
		}		
		return result;
	}

	private static NodeList getXMLNodes(String xmlURL, String tagElementsName) {
		Document doc = getXMLDocument(xmlURL);		
		return doc.getElementsByTagName(tagElementsName);
	}
	
	private static Document getXMLDocument(String xmlURL){
		Document doc = null;
		try {
			DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();			
			doc = db.parse(new File(xmlURL));
			doc.getDocumentElement().normalize();			
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return doc;
	}

	private static String getValueByChildNodeName(Node parentNode, String childNodeName) {
		Node childNode = ((Element)parentNode).getElementsByTagName(childNodeName).item(0);
		Node childContentNode = childNode.getChildNodes().item(0);		
		return (childContentNode==null)?(""):(childContentNode.getNodeValue());
	}

	public static HashMap<String, String> getParamsFromFile(String configUrl) {
		HashMap<String, String> result = new HashMap<String, String>();
		NodeList nodelist = getXMLNodes(configUrl, "config");
		for (int i = 0; i < nodelist.getLength(); i++) {
			Node node = nodelist.item(i);
			if(node.getNodeType()==Node.ELEMENT_NODE){	
				result.put("xmlURL",getValueByChildNodeName(node, "xmlURL"));
				result.put("playListOut",getValueByChildNodeName(node, "playListOut"));
			}
		}				
		return result;
	}
}